package com.heima.behavior.service.impl;


import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * author by itheima
 *
 * @Date 2022/3/8
 * Description
 */
@Service
public class ApBehaviorEntryServiceImpl implements ApBehaviorEntryService {
    /**
     * 查询行为实体
     *
     * @param userId  用户id
     * @param equipmentId  设备id
     * @return
     */
    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public ApBehaviorEntry findByUserIdOrEquipmentId(Integer userId, Integer equipmentId) {
//1. 判断userId是否为空
        if (userId == null&& equipmentId==null) {
            return null;
        }
        ApBehaviorEntry apBehaviorEntry = new ApBehaviorEntry();
        if (userId!=null){
            Query query = Query.query(Criteria.where("refId").is(userId).and("type").is(ApBehaviorEntry.Type.USER.getCode()));
            ApBehaviorEntry apBehavior = mongoTemplate.findOne(query, ApBehaviorEntry.class);
            if (apBehavior==null){
                apBehaviorEntry.setType((short)0);
                apBehaviorEntry.setRefId(userId);
                apBehaviorEntry.setCreatedTime(new Date());
                mongoTemplate.save(apBehaviorEntry);
                return apBehaviorEntry;
            }else {
                return apBehavior;
            }
        }else {
            //userId为空 设备id不为空
            Query query = Query.query(Criteria.where("refId").is(equipmentId).and("type").is(ApBehaviorEntry.Type.EQUIPMENT.getCode()));
            ApBehaviorEntry apBehavior = mongoTemplate.findOne(query, ApBehaviorEntry.class);
            if (apBehavior==null){
                apBehaviorEntry.setType((short)1);
                apBehaviorEntry.setRefId(equipmentId);
                apBehaviorEntry.setCreatedTime(new Date());
                mongoTemplate.save(apBehaviorEntry);
                return apBehaviorEntry;
            }
            return apBehavior;
        }
    }
}
